using System;
using System.Collections.Generic;
using System.Text;

namespace BEncode.Types
{
    public class BEInt
    {
        private int decValue;
        private string encValue;

        public int DecodedValue
        {
            get { return decValue; }
        }
        
        public string EncodedValue
        {
            get { return encValue; }
        }


        public BEInt():this(0)
        {

        }
        public BEInt(int integer)
        {
            this.decValue = integer;
            this.encValue = Encode(integer);
        }
        public BEInt(string bnInt)
        {
            this.decValue = Decode(bnInt);
            this.encValue = bnInt;
        }

        public static int Decode(string string2decode)
        {
            int rtn = 0;

            if (string2decode != string.Empty)
            {
                if (string2decode.Length > 2 && string2decode[0] == 'i' && string2decode[string2decode.Length - 1] == 'i')
                {
                    rtn = int.Parse(string2decode.Substring(1, string2decode.Length - 2));
                }
                else
                {
                    throw new Exception("This is not a bencoded integer");
                }
            }
            else
            {
                
                throw new Exception("String to decode is empty!");
            }
            
            return rtn;
        }

        public static string Encode(int int2encode)
        {
            char start = 'i';
            char end = 'e';
            StringBuilder stringb = new StringBuilder(start);
            stringb.Append(int2encode.ToString()).Append(end);

            return stringb.ToString();
        }

    }
}
